from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from datetime import datetime

from ..database import get_db
from ..models.user import User
from ..models.template import Template
from ..auth.auth import get_current_active_user

router = APIRouter()

class TemplateCreate(BaseModel):
    name: str
    description: str = ""
    content: str
    template_type: str = "outline"
    format_type: str = "markdown"

class TemplateUpdate(BaseModel):
    name: str = None
    description: str = None
    content: str = None
    template_type: str = None
    format_type: str = None

class TemplateResponse(BaseModel):
    id: int
    name: str
    description: str
    content: str
    template_type: str
    format_type: str
    created_at: datetime
    updated_at: datetime
    creator_id: int
    
    class Config:
        from_attributes = True

@router.post("/", response_model=TemplateResponse)
async def create_template(
    template: TemplateCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    db_template = Template(
        name=template.name,
        description=template.description,
        content=template.content,
        template_type=template.template_type,
        format_type=template.format_type,
        creator_id=current_user.id
    )
    db.add(db_template)
    db.commit()
    db.refresh(db_template)
    return db_template

@router.get("/", response_model=List[TemplateResponse])
async def list_templates(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    templates = db.query(Template).filter(
        Template.creator_id == current_user.id
    ).all()
    return templates

@router.get("/{template_id}", response_model=TemplateResponse)
async def get_template(
    template_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(
        Template.id == template_id,
        Template.creator_id == current_user.id
    ).first()
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    return template

@router.put("/{template_id}", response_model=TemplateResponse)
async def update_template(
    template_id: int,
    template_update: TemplateUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(
        Template.id == template_id,
        Template.creator_id == current_user.id
    ).first()
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    update_data = template_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(template, field, value)
    
    db.commit()
    db.refresh(template)
    return template

@router.delete("/{template_id}")
async def delete_template(
    template_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(
        Template.id == template_id,
        Template.creator_id == current_user.id
    ).first()
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    db.delete(template)
    db.commit()
    return {"message": "模板删除成功"} 